package cn.tedu.baking.controller;

import cn.tedu.baking.commons.response.JsonResult;
import jdk.nashorn.internal.runtime.JSONFunctions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/v1/")
public class UploadController {
    @Value("${file-path}")
    private String dirPath;

    @PostMapping("upload")
    public JsonResult upload(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        //截取后缀名  a.jpg     .jpg
        String suffix = fileName.substring(fileName.lastIndexOf('.'));
        //得到唯一文件名  UUID.randomUUID()得到一个唯一标识
        fileName = UUID.randomUUID()+suffix;
        System.out.println("filename="+fileName);

        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = sdf.format(new Date());
        // d:/files/2023/09/13/
        File dirFile = new File(dirPath+datePath);
        if (!dirFile.exists()){
            dirFile.mkdirs();//如果不存在则创建
        }
        //d:/files/2023/09/13/xxxxx.jpg
        String filePath = dirPath+datePath+fileName;
        //把接收到的文件保存到指定的路径  异常抛出
        file.transferTo(new File(filePath));
        //把上传成功的文件路径响应给客户端  /2023/09/13/xxxxx.jpg
        return JsonResult.ok(datePath+fileName);
    }

    @PostMapping("remove")
    public JsonResult remove(String url){
        //删除磁盘上的文件  /2023.....jpg
        new File(dirPath+url).delete();
        return JsonResult.ok();
    }
}
